<template>
 <v-app>
    <v-app-bar
      app
      clipped-right
      flat
      height="56"
    >
      <v-spacer></v-spacer>
    </v-app-bar>

    <v-navigation-drawer
      app
      dark
    >
      <v-navigation-drawer
        absolute
        expand-on-hover
      >
        <v-list>
          <template v-for="item in user.menu">
            <v-list-group
              v-if=" item.children &&  item.children.length > 0"
              :key="item.id"
              active-class="white--text"
              :group="item.children.flatMap(e => '^' + e.uri).join('|')"
            >
              <template v-slot:activator>
                <v-list-item-content>
                  <v-list-item-title v-text="item.title"></v-list-item-title>
                </v-list-item-content>
              </template>

              <template v-slot:prependIcon>
                <v-icon>{{ item.icon ? item.icon : "mdi-folder"}}</v-icon>
              </template>


              <v-list-item
                v-for="item in item.children"
                :key="item.id"
                link
                :to="item.uri"
                active-class="white--text"
              >
                <v-list-item-icon>

                </v-list-item-icon>
                <v-list-item-content>
                  <v-list-item-title>{{ item.title }}</v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-group>

            <v-list-item
              v-else
              :key="item.id"
              link
              :to="item.uri"
              active-class="white--text"
            >
              <v-list-item-icon>
                  <v-icon>{{ item.icon ? item.icon : "mdi-folder"}}</v-icon>
              </v-list-item-icon>
              <v-list-item-content>
                <v-list-item-title>{{ item.title }}</v-list-item-title>
              </v-list-item-content>
            </v-list-item>

          </template>
        </v-list>
      </v-navigation-drawer>

      <v-list
        class="pl-14"
        shaped
      >
        <v-list-item link :to="`/chat/room/0`">
          <v-list-item-avatar
            color="error"
            rounded
            size="36"
            class="overflow-visible"
          >
           <v-badge
              color="red"
              :content="publicMsgCnt"
              :value="publicMsgCnt"
            >
              <span class="white--text subtitle-1">公</span>
            </v-badge>
          </v-list-item-avatar>
          <v-list-item-content>
            <v-list-item-title>公共大厅</v-list-item-title>
            <v-list-item-subtitle v-if="publicMsg">{{publicMsg.msg}}</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>

        <v-list-item
          v-for="room in rooms"
          :key="room.id"
          link
          :to="`/chat/room/${room.room_id}`"
        >

          <v-list-item-avatar
            class="overflow-visible"
            color="primary"
            rounded
            size="36"
          >
            <v-badge
              color="red"
              :content="room.new_cnt"
              :value="room.new_cnt"
            >
              <span class="white--text subtitle-1">{{room.owner.substr(0,1)}}</span>
            </v-badge>
          </v-list-item-avatar>

          <v-list-item-content>
            <v-list-item-title> {{ room.owner }}</v-list-item-title>
            <v-list-item-subtitle v-if="room.msg">{{room.msg.msg}}</v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>


    <v-main class="grey lighten-4">
      <router-view></router-view>
    </v-main>

  </v-app>
</template>

<script>
import { mapGetters } from 'vuex';
import Echo from 'laravel-echo';

export default {
    data () {
        return {
            mini: true,
            drawer: null,
            rooms: [],
            publicMsg: null,
            publicMsgCnt: 0,
            id: 0
        }
    },
    computed: {
        ...mapGetters([
            'user',
            'token',
            'uid',
            'inchat'
        ]),
    },

    created() {
        window.Echo = new Echo({
            broadcaster: 'pusher',
            wsHost: PUSHER_HOST,
            key: PUSHER_APP_KEY,
            cluster: PUSHER_APP_CLUSTER,
            forceTLS: false,
            enabledTransports: ['ws', 'wss'],
            auth: { headers: { 'Authorization': 'Bearer ' + this.token } }
        });

        this.id = parseInt(this.$route.params.id);
        this.init();

        this.$store.commit("inchat", true);
        this.$store.commit("chat_msg_new", false);

        if (window.ChatNotify) {
          window.ChatNotify.stopListening(`.msg.new`, this.displayNotification);
        }

    },

    beforeRouteUpdate(to, from, next) {
        this.id = parseInt(to.params.id);
        this.resetBadge();
        next();
    },

    beforeDestroy() {
      this.$store.commit("inchat", false);

      window.ChatNotify = window.Echo.private(`new-msg`);
      window.ChatNotify.listen('.msg.new', this.displayNotification);
    },

    methods: {
        resetBadge() {
            const room_id = this.id;
            const idx =  this.rooms.findIndex((v) => v.room_id == room_id);
            if (idx >= 0) {
                this.rooms[idx].new_cnt = 0;
            }
        },
        init() {
            const that = this;
            window.Echo.private(`room.0`)
                .listen('.room.msg.new', (msg)=> {
                    that.publicMsg = msg;
                    if (that.id !== 0) {
                         that.publicMsgCnt += 1;
                    }
            });


            window.Echo.private(`room-list`).subscribed(() => {
              that.loadRooms();
            }).listen('.room.list.new', (data)=> {
              if (data.room_id == 0) return;
              const idx =  that.rooms.findIndex((v) => v.room_id == data.room_id);
              if (idx == -1) {
                  that.rooms.unshift({...data, msg: null, new_cnt: 0});
                  window.Echo.private(`room.${data.room_id}`)
                      .listen('.room.msg.new', (msg)=> {
                        const room_id = data.room_id;
                        const idx =  that.rooms.findIndex((v) => v.room_id == room_id);
                        if  (idx >= 0) {
                            // 收到消息，自动置顶
                            const room = that.rooms.splice(idx, 1);
                            room[0].msg = msg;
                            if (that.id !== room_id) {
                                room[0].new_cnt += 1;
                            }
                            that.rooms.unshift(room[0]);
                        }
                });
              }
            });
        },
        displayNotification(msg) {
          if (this.inchat) return;
          if (this.uid == msg.sender_id) return;

          this.$store.commit("chat_msg_new", true);
          this.$toast.open({
              message: "您有一条新在线客服的消息",
              type: 'default',
              position: 'top-right',
          });
        },
        loadRooms() {
            axios.get(`/chat/room/recent`).then((response) => {
                if (response.data.code == 0) {
                }
            })
            .catch(function () {})
            .then(function () {
            });
        },
    }
}
</script>

<style></style>
